package couk.mmtdigital.sm.control.commands
{
	import couk.mmtdigital.sm.ApplicationFacade;
	import couk.mmtdigital.sm.model.FileListProxy;
	import couk.mmtdigital.sm.model.UserProxy;
	
	import flash.events.DataEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;

	public class UploadCommand extends SimpleCommand implements ICommand
	{
		private var uploadURL:URLRequest;
		private var uploadVars:URLVariables;
		private var file:FileReference;
		
		override public function execute(notification:INotification):void{
			file = notification.getBody() as FileReference; trace("uploadCommand called, fileName: "+file.name);
			var userProxy:UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
			var fileListProxy:FileListProxy = facade.retrieveProxy(FileListProxy.NAME) as FileListProxy;
			
			uploadVars = new URLVariables();
			uploadVars.user = userProxy.username;
			uploadVars.pass = userProxy.password;
			uploadVars.dir = fileListProxy.currentFile;			
			trace("uploadVars: user:"+uploadVars.user);
			
			uploadURL = new URLRequest();
			uploadURL.url = "http://localhost/sm/amfphp/services/sm/uploader.php";
			uploadURL.contentType = "multipart/form-data";
			uploadURL.data = uploadVars;
			uploadURL.method = URLRequestMethod.POST;
			
			file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onDataComplete);
			file.addEventListener(ProgressEvent.PROGRESS, onProgressUpdate);
			file.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			
			file.upload(uploadURL, "uploadFile", false);
		}
		
		private function onDataComplete(evt:DataEvent):void{
			trace("upload complete, recieved: "+evt.data);
			if(evt.data == "success"){
				Alert.show("You upload was successful", "Upload Status");
				sendNotification(ApplicationFacade.FILELIST);
			}
		}
		
		private function onProgressUpdate(evt:ProgressEvent):void{
			trace("Loaded: "+evt.bytesLoaded+"/"+evt.bytesTotal);
			sendNotification(ApplicationFacade.PROGRESSUPDATE, evt);
		}
		
		private function onIOError(evt:IOErrorEvent):void{
			trace("there was an IO Error. "+evt.errorID);
		}
		
		private function onSecurityError(evt:SecurityErrorEvent):void{
			trace("there was a security error");
		}
		
	}
}